package com.loongxun.playwithyou.ui.activity.user;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.loongxun.playwithyou.ApiInterface;
import com.loongxun.playwithyou.App;
import com.loongxun.playwithyou.R;
import com.loongxun.playwithyou.ali.ToAliActivity;
import com.loongxun.playwithyou.bean.Member;
import com.loongxun.playwithyou.bean.SendRequest;
import com.loongxun.playwithyou.network.MyHttpClientRespenseHandler;
import com.loongxun.playwithyou.network.nHttpClient;
import com.loongxun.playwithyou.util.DensityUtils;
import com.loongxun.playwithyou.util.ToastView;
import com.loongxun.playwithyou.view.swipemenulistview.BaseSwipListAdapter;
import com.loongxun.playwithyou.view.swipemenulistview.SwipeMenu;
import com.loongxun.playwithyou.view.swipemenulistview.SwipeMenuCreator;
import com.loongxun.playwithyou.view.swipemenulistview.SwipeMenuItem;
import com.loongxun.playwithyou.view.swipemenulistview.SwipeMenuListView;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 我的收藏
 * Created by Administrator on 2017/8/22.
 */
public class UserCollAcitvity extends Activity {

    private List<Member> mAppList = new ArrayList<>();
    private AppAdapter mAdapter;
    private SwipeMenuListView mListView;

    private Context context;
    private SharedPreferences share;
    private SharedPreferences.Editor editor;
    private SendRequest send;
    private String userId;

    //标题
    private TextView tv_top_title;

    private ImageLoader imageLoader = ImageLoader.getInstance();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_coll);

        context = UserCollAcitvity.this;
        share = context.getSharedPreferences("userInfo", 0);
        editor = share.edit();
        userId = share.getString("user_id", "");

        collList();
        findViewById(R.id.iv_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        tv_top_title = (TextView) findViewById(R.id.tv_top_title);
        tv_top_title.setText("我的收藏");

        mListView = (SwipeMenuListView) findViewById(R.id.listView);

        // step 1. 创建控件
        SwipeMenuCreator creator = new SwipeMenuCreator() {
            @Override
            public void create(SwipeMenu menu) {
                // create "open" item
                SwipeMenuItem openItem = new SwipeMenuItem(getApplicationContext());
                // set item background
                openItem.setBackground(new ColorDrawable(Color.rgb(0xd9, 0x2f, 0x00)));
                // set item width
                openItem.setWidth(DensityUtils.dp2px(context,80));
                // set item title
                openItem.setTitle("删除");
                // set item title fontsize
                openItem.setTitleSize(16);
                // set item title font color
                openItem.setTitleColor(Color.WHITE);
                // add to menu
                menu.addMenuItem(openItem);
            }
        };
        // set creator
        mListView.setMenuCreator(creator);

        // step 2. 点击事件
        mListView.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
                Member item = mAppList.get(position);
                switch (index) {
                    case 0:
                        delColl(item.getMember_id()+"");
                        break;
                }
                return false;
            }
        });

    }

    private void collList() {
        try {
            send = new SendRequest();
            send.userId = userId;
            //个人中心我的收藏
            nHttpClient.getAll(ApiInterface.COLL_LIST, send.toisMemberJson().toString(), collListHandler);
        }catch (Exception e){
            ToastView toast = new ToastView(context, "参数错误");
            toast.show();
        }
    }

    private void delColl(String memberId) {
        try {
            send = new SendRequest();
            send.userId = userId;
            send.memberId = memberId;
            //删除收藏
            nHttpClient.getAll(ApiInterface.DEL_COLL, send.toDelCollJson().toString(), delCollHandler);
        }catch (Exception e){
            ToastView toast = new ToastView(context, "参数错误");
            toast.show();
        }
    }

    class AppAdapter extends BaseSwipListAdapter {

        @Override
        public int getCount() {
            return mAppList.size();
        }

        @Override
        public Member getItem(int position) {
            return mAppList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = View.inflate(getApplicationContext(), R.layout.item_coll_list, null);
                new ViewHolder(convertView);
            }
            ViewHolder holder = (ViewHolder) convertView.getTag();
            Member item = getItem(position);
            imageLoader.displayImage(ApiInterface.IMAGES + item.getMember_img(), holder.iv_item_coll_img, App.options);
            holder.tv_item_coll_name.setText(item.getMember_name());
            holder.tv_item_coll_num.setText(item.getClick_num()+"");
            holder.ll_item_coll_game.removeAllViews();
            ImageView dotIv;
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(DensityUtils.dp2px(context, 40), DensityUtils.dp2px(context, 40));
            for (int i = 0; i < item.getGameImgs().size(); i++) {
                dotIv = new ImageView(context);
                //设置点的间距
                params.setMargins(DensityUtils.dp2px(context, 5), DensityUtils.dp2px(context, 5), 0,DensityUtils.dp2px(context, 5));
                dotIv.setLayoutParams(params);
                imageLoader.displayImage(ApiInterface.IMAGES + item.getGameImgs().get(i), dotIv, App.options);
                //添加点到view上
                holder.ll_item_coll_game.addView(dotIv);
            }
            return convertView;
        }

        class ViewHolder {
            ImageView iv_item_coll_img;
            TextView tv_item_coll_name,tv_item_coll_num;
            LinearLayout ll_item_coll_game;

            public ViewHolder(View view) {
                iv_item_coll_img = (ImageView) view.findViewById(R.id.iv_item_coll_img);
                tv_item_coll_name = (TextView) view.findViewById(R.id.tv_item_coll_name);
                tv_item_coll_num = (TextView) view.findViewById(R.id.tv_item_coll_num);
                ll_item_coll_game = (LinearLayout) view.findViewById(R.id.ll_item_coll_game);
                view.setTag(this);
            }
        }

    }

    private MyHttpClientRespenseHandler delCollHandler = new MyHttpClientRespenseHandler() {

        @Override
        public void success(JSONObject json) {
            Integer succeed = json.optJSONObject("status").optInt("succeed", 0);
            if (succeed == 1) {
                collList();
                String error_desc = json.optJSONObject("status").optString("error_desc");
                new ToastView(context, error_desc).show();
            }else {
                String error_desc = json.optJSONObject("status").optString("error_desc");
                new ToastView(context, error_desc).show();
            }
        }

        @Override
        public void faile(String json) {
            new ToastView(context, json).show();
        }
    };

    private MyHttpClientRespenseHandler collListHandler = new MyHttpClientRespenseHandler() {

        @Override
        public void success(JSONObject json) {
            Integer succeed = json.optJSONObject("status").optInt("succeed", 0);
            JSONArray itemArray;
            if (succeed == 1) {
                try {
                    itemArray = json.getJSONObject("data").getJSONArray("memberList");
                    mAppList.clear();
                    for(int i = 0;i < itemArray.length();i++) {
                        JSONObject subItemObject = itemArray.getJSONObject(i);
                        Member member = new Member();
                        member.setMember_id(subItemObject.optInt("member_id", 0));
                        member.setClick_num(subItemObject.optInt("click_num", 0));
                        member.setMember_address(subItemObject.optString("member_address"));
                        member.setMember_img(subItemObject.optString("member_img"));
                        member.setMember_name(subItemObject.optString("member_name"));
                        List<String> imgs = new ArrayList<>();
                        if (!"null".equals(subItemObject.getString("memberGames"))) {
                            itemArray = subItemObject.getJSONArray("memberGames");
                            for(int j = 0;j < itemArray.length();j++) {
                                JSONObject jsonObject = itemArray.getJSONObject(j);
                                imgs.add(jsonObject.optString("game_logo"));
                            }
                        }
                        member.setGameImgs(imgs);
                        mAppList.add(member);
                    }
                    if (mAdapter == null) {
                        mAdapter = new AppAdapter();
                        mListView.setAdapter(mAdapter);
                    }else {
                        mAdapter.notifyDataSetChanged();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }else {
                String error_desc = json.optJSONObject("status").optString("error_desc");
                new ToastView(context, error_desc).show();
            }
        }

        @Override
        public void faile(String json) {
            new ToastView(context, json).show();
        }
    };
    

}
